package UIFree.behavior
{
	import UIUtils.uif_util;
	
	import flash.display.DisplayObject;
	
	public class uif_baseBehavior extends Object {
		private var _component	: DisplayObject;
		private var _propSave	: Object;
		private var _options	: Object;
		protected static const _running: Array = [];
		
/*		public static const BEHAVIORSTART: String 	= 'BEHAVIORSTART';
		public static const BEHAVIOREND: String 	= 'BEHAVIOREND';*/
		public function uif_baseBehavior(a_component: DisplayObject, a_options: Object) {
			super();
			_component 	= a_component;
			_options	= uif_util.union(defaultOptions(), a_options);
			_propSave 	= new Object();
			begin();
		}
		
		protected function defaultOptions(): Object {
			return {};
		}
		
		protected function get component(): DisplayObject {
			return _component;
		}
		
		protected function get options(): Object {
			return _options;
		}
		
		private function begin(): void {
			var rIndex: int = getBehaviorIndex(component);
			if (rIndex > -1) _running[rIndex][1].cancel(); 
			saveState();
			beforeStart();
			run(afterEnd);
		}
		
		public function cancel(): void {
			restoreState();
			removeRunning();
		}
		
		private function removeRunning(): void {
			var rIndex: int = getBehaviorIndex();
			if (rIndex > -1) _running.splice(rIndex, 1);
		} 
		
		protected function beforeStart(): void {
			_running.push([component, this]);
		}
		
		protected function getBehaviorIndex(a_component: DisplayObject=null): int {
			for (var i: int =0; i<_running.length; i++)
				if (((a_component != null) && (a_component == _running[i][0])) || 
					(_running[i][1] == this)) return i;
			return -1;
		}
		
		protected function afterEnd(): void {
			removeRunning();
			_component 	= null;
			_options	= null;
		}
		
		protected function pushValue(propertyName: String, value: Object): void {
			_propSave[propertyName] = value;
		}
		
		protected function popValue(propertyName: String): Object {
			var value: Object = _propSave[propertyName];
			delete(_propSave[propertyName]);
			return value;
		}
		
		protected function getValue(propertyName: String): Object {
			return _propSave[propertyName];
		}
		
		protected function run(afterEnd: Function): void {
			
		}
		
		protected function saveState(): void {
			
		}
		
		protected function restoreState(): void {
			
		} 
	}
}